package wxcloud

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"github.com/mars/internal/admin/core/domain"
	"github.com/mars/internal/pkg/wxcloud"
	"github.com/mars/pkg/loggers"
)

const (
	orderCollection = "order"
)

// orderGatewayImpl 订单网关实现
type orderGatewayImpl struct {
	wxcloud *wxcloud.WxCloudClient
}

// newOrderGatewayImpl 创建订单网关实现
func newOrderGatewayImpl(wxcloud *wxcloud.WxCloudClient) domain.OrderGateway {
	return &orderGatewayImpl{
		wxcloud: wxcloud,
	}
}

// GetOrderList 获取订单列表
func (o *orderGatewayImpl) GetOrderList(ctx interface{}, params domain.OrderQueryParams) ([]domain.Order, int64, error) {
	c := ctx.(context.Context)

	// 构建查询条件
	queryBuilder := wxcloud.NewQueryBuilder(orderCollection)

	// 处理筛选条件
	if params.Status != "" {
		queryBuilder.Where("status", string(params.Status))
	}

	if params.PaymentMethod != "" {
		queryBuilder.Where("paymentMethod", string(params.PaymentMethod))
	}

	if params.IsVipOrder != nil {
		queryBuilder.Where("isVipOrder", *params.IsVipOrder)
	}

	if params.ProductType != "" {
		queryBuilder.Where("items.productType", string(params.ProductType))
	}

	if params.StartTime != nil {
		queryBuilder.Where("createTime", map[string]interface{}{"$gte": *params.StartTime})
	}

	if params.EndTime != nil {
		queryBuilder.Where("createTime", map[string]interface{}{"$lte": *params.EndTime})
	}

	if params.MinAmount != nil {
		queryBuilder.Where("totalAmount", map[string]interface{}{"$gte": *params.MinAmount})
	}

	if params.MaxAmount != nil {
		queryBuilder.Where("totalAmount", map[string]interface{}{"$lte": *params.MaxAmount})
	}

	if params.HasVipDiscount != nil {
		queryBuilder.Where("items.hasVipDiscount", *params.HasVipDiscount)
	}

	// 处理关键字搜索
	if params.Keyword != "" {
		// 构建模糊搜索条件（订单号、用户openid、商品名称）
		keywordCondition := map[string]interface{}{
			"$or": []map[string]interface{}{
				{"orderNo": map[string]interface{}{"$regex": params.Keyword}},
				{"openid": map[string]interface{}{"$regex": params.Keyword}},
				{"items.productName": map[string]interface{}{"$regex": params.Keyword}},
			},
		}
		queryBuilder.Where("$or", keywordCondition["$or"])
	}

	// 处理排序
	orderDirection := "desc"
	if params.Order != "" {
		orderDirection = params.Order
	}
	sortField := "createTime"
	if params.Sort != "" {
		sortField = params.Sort
	}
	queryBuilder.OrderBy(sortField, orderDirection)

	// 处理分页
	offset := (params.Page - 1) * params.PageSize
	queryBuilder.Skip(offset).Limit(params.PageSize)

	// 执行查询
	queryString := queryBuilder.BuildQueryString()
	loggers.Info(c, "Executing order query", "query", queryString)

	resp, err := o.wxcloud.DatabaseQuery(c, o.wxcloud.EnvId(), queryString)
	if err != nil {
		loggers.Error(c, "Failed to query orders from database", err)
		return nil, 0, fmt.Errorf("failed to query orders: %w", err)
	}

	// 解析查询结果
	var orders []domain.Order
	for _, dataStr := range resp.Data {
		var order domain.Order
		if err := json.Unmarshal([]byte(dataStr), &order); err != nil {
			loggers.Error(c, "Failed to unmarshal order data", err, "data", dataStr)
			continue
		}
		orders = append(orders, order)
	}

	return orders, int64(resp.Pager.Total), nil
}

// GetOrder 获取订单详情
func (o *orderGatewayImpl) GetOrder(ctx interface{}, orderID string) (*domain.Order, error) {
	c := ctx.(context.Context)

	queryBuilder := wxcloud.NewQueryBuilder(orderCollection)
	queryBuilder.Where("_id", orderID)

	queryString := queryBuilder.BuildQueryString()
	resp, err := o.wxcloud.DatabaseQuery(c, o.wxcloud.EnvId(), queryString)
	if err != nil {
		return nil, fmt.Errorf("failed to query order: %w", err)
	}

	if len(resp.Data) == 0 {
		return nil, fmt.Errorf("order not found")
	}

	var order domain.Order
	if err := json.Unmarshal([]byte(resp.Data[0]), &order); err != nil {
		return nil, fmt.Errorf("failed to unmarshal order data: %w", err)
	}

	return &order, nil
}

// UpdateOrderStatus 更新订单状态
func (o *orderGatewayImpl) UpdateOrderStatus(ctx interface{}, orderID string, status domain.OrderStatus) error {
	c := ctx.(context.Context)

	updateData := map[string]interface{}{
		"status":     string(status),
		"updateTime": time.Now().Unix(),
	}

	whereCondition := map[string]interface{}{
		"_id": orderID,
	}

	updateQuery := wxcloud.BuildUpdateString(orderCollection, whereCondition, updateData)

	_, _, err := o.wxcloud.DatabaseUpdate(c, o.wxcloud.EnvId(), updateQuery)
	if err != nil {
		return fmt.Errorf("failed to update order status: %w", err)
	}

	return nil
}

// ProcessRefund 处理退款
func (o *orderGatewayImpl) ProcessRefund(ctx interface{}, orderID string, reason string, amount *int) error {
	// TODO: 实现退款处理逻辑
	return fmt.Errorf("refund processing not implemented")
}

// GetOrderStats 获取订单统计信息
func (o *orderGatewayImpl) GetOrderStats(ctx interface{}) (*domain.OrderStats, error) {
	// TODO: 实现订单统计
	return nil, fmt.Errorf("order stats not implemented")
}

// SearchOrders 搜索订单
func (o *orderGatewayImpl) SearchOrders(ctx interface{}, keyword string) ([]domain.Order, error) {
	c := ctx.(context.Context)

	queryBuilder := wxcloud.NewQueryBuilder(orderCollection)

	// 构建搜索条件
	keywordCondition := map[string]interface{}{
		"$or": []map[string]interface{}{
			{"orderNo": map[string]interface{}{"$regex": keyword}},
			{"openid": map[string]interface{}{"$regex": keyword}},
			{"items.productName": map[string]interface{}{"$regex": keyword}},
		},
	}
	queryBuilder.Where("$or", keywordCondition["$or"])

	// 按创建时间倒序
	queryBuilder.OrderBy("createTime", "desc")

	// 限制结果数量
	queryBuilder.Limit(100)

	queryString := queryBuilder.BuildQueryString()
	resp, err := o.wxcloud.DatabaseQuery(c, o.wxcloud.EnvId(), queryString)
	if err != nil {
		return nil, fmt.Errorf("failed to search orders: %w", err)
	}

	var orders []domain.Order
	for _, dataStr := range resp.Data {
		var order domain.Order
		if err := json.Unmarshal([]byte(dataStr), &order); err != nil {
			continue
		}
		orders = append(orders, order)
	}

	return orders, nil
}

// GetOrdersByStatus 根据状态查询订单
func (o *orderGatewayImpl) GetOrdersByStatus(ctx interface{}, status domain.OrderStatus) ([]domain.Order, error) {
	c := ctx.(context.Context)

	queryBuilder := wxcloud.NewQueryBuilder(orderCollection)
	queryBuilder.Where("status", string(status))
	queryBuilder.OrderBy("createTime", "desc")
	queryBuilder.Limit(1000)

	queryString := queryBuilder.BuildQueryString()
	resp, err := o.wxcloud.DatabaseQuery(c, o.wxcloud.EnvId(), queryString)
	if err != nil {
		return nil, fmt.Errorf("failed to query orders by status: %w", err)
	}

	var orders []domain.Order
	for _, dataStr := range resp.Data {
		var order domain.Order
		if err := json.Unmarshal([]byte(dataStr), &order); err != nil {
			continue
		}
		orders = append(orders, order)
	}

	return orders, nil
}

// GetOrdersByPaymentMethod 根据支付方式查询订单
func (o *orderGatewayImpl) GetOrdersByPaymentMethod(ctx interface{}, paymentMethod domain.PaymentMethod) ([]domain.Order, error) {
	c := ctx.(context.Context)

	queryBuilder := wxcloud.NewQueryBuilder(orderCollection)
	queryBuilder.Where("paymentMethod", string(paymentMethod))
	queryBuilder.OrderBy("createTime", "desc")
	queryBuilder.Limit(1000)

	queryString := queryBuilder.BuildQueryString()
	resp, err := o.wxcloud.DatabaseQuery(c, o.wxcloud.EnvId(), queryString)
	if err != nil {
		return nil, fmt.Errorf("failed to query orders by payment method: %w", err)
	}

	var orders []domain.Order
	for _, dataStr := range resp.Data {
		var order domain.Order
		if err := json.Unmarshal([]byte(dataStr), &order); err != nil {
			continue
		}
		orders = append(orders, order)
	}

	return orders, nil
}

// GetVipOrders 获取VIP订单
func (o *orderGatewayImpl) GetVipOrders(ctx interface{}) ([]domain.Order, error) {
	c := ctx.(context.Context)

	queryBuilder := wxcloud.NewQueryBuilder(orderCollection)
	queryBuilder.Where("isVipOrder", true)
	queryBuilder.OrderBy("createTime", "desc")
	queryBuilder.Limit(1000)

	queryString := queryBuilder.BuildQueryString()
	resp, err := o.wxcloud.DatabaseQuery(c, o.wxcloud.EnvId(), queryString)
	if err != nil {
		return nil, fmt.Errorf("failed to query vip orders: %w", err)
	}

	var orders []domain.Order
	for _, dataStr := range resp.Data {
		var order domain.Order
		if err := json.Unmarshal([]byte(dataStr), &order); err != nil {
			continue
		}
		orders = append(orders, order)
	}

	return orders, nil
}

// ExportOrders 导出订单数据
func (o *orderGatewayImpl) ExportOrders(ctx interface{}, params domain.OrderQueryParams) ([]domain.Order, error) {
	// 导出时不限制数量，但设置一个合理的上限
	params.PageSize = 10000
	params.Page = 1

	orders, _, err := o.GetOrderList(ctx, params)
	if err != nil {
		return nil, fmt.Errorf("failed to export orders: %w", err)
	}

	return orders, nil
}
